package com.yakami.ocean.view.activity;

import android.os.Bundle;
import android.widget.LinearLayout;

import com.annimon.stream.Stream;
import com.yakami.ocean.AppManager;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.TestRecord;
import com.yakami.ocean.utils.Tools;
import com.yakami.ocean.view.activity.base.BaseHoldBackTabsActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yakami.ocean.AppManager.context;

/**
 * Created by Yakami on 2016/7/6, enjoying it!
 */

public class TestRecordActivity extends BaseHoldBackTabsActivity {

    @Bind(R.id.chart_container) LinearLayout mChartContainer;

    private LineChartData data;
    private int numberOfLines = 1;
    private int maxNumberOfLines = 4;
    private int numberOfPoints = 12;
    float[][] randomNumbersTab = new float[maxNumberOfLines][numberOfPoints];
    private ValueShape shape = ValueShape.CIRCLE;
    private boolean isCubic = false;
    private boolean isFilled = false;
    private boolean hasAxes = true;
    private boolean hasAxesNames = true;
    private boolean hasLabels = true;
    private boolean hasLabelForSelected = false;
    private boolean hasLines = true;
    private boolean hasPoints = true;
    private boolean pointsHaveDifferentColor;

    private Map<String, List<Integer>> mData;
    private List<LineChartView> mChartList;

    @Override
    protected void onCreate(Bundle savedInstanceBundle) {
        super.onCreate(savedInstanceBundle);
        mTitle.setText(mRes.getString(R.string.test_record));

        getData();
    }

    private void resetViewport() {
        // Reset viewport height range to (0,100)
        Stream.of(mChartList)
                .forEach(item -> {
                    final Viewport v = new Viewport(item.getMaximumViewport());
                    v.bottom = 0;
                    v.top = 100;
                    v.left = 0;
                    v.right = numberOfPoints - 1;
                    item.setMaximumViewport(v);
                    item.setCurrentViewport(v);
                });
    }

    private void getData() {
        mData = new HashMap<>();
        ServerAPI.getOceanAPI()
                .getTestRecord()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(list -> {
                    for (TestRecord item : list.list) {
                        if (mData.containsKey(item.getTestName())) {
                            mData.get(item.getTestName()).add(item.getScore());
                        } else {
                            List<Integer> itemList = new ArrayList<>();
                            itemList.add(item.getScore());
                            mData.put(item.getTestName(), itemList);
                        }
                    }

                    if (mData.size() == 0) {
                        Tools.toast(AppManager.context, mRes.getString(R.string.empty_test_record));
                        return;
                    }

                    initChartLayout();
                    generateData();
                    resetViewport();

                    Stream.of(mChartList)
                            .forEach(item -> {
                                item.setViewportCalculationEnabled(false);
                            });
                }, Throwable::printStackTrace);


//        for (int i = 0; i < maxNumberOfLines; ++i) {
//            for (int j = 0; j < numberOfPoints; ++j) {
//                randomNumbersTab[i][j] = (float) Math.random() * 100f;
//            }
//        }
    }

    private void initChartLayout() {
        mChartList = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
            LineChartView chart = new LineChartView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    Tools.dp2px(AppManager.context, 250), 1.0f);
            chart.setLayoutParams(params);
            mChartContainer.addView(chart);
            mChartList.add(chart);
        }
    }

    private void generateData() {
        int i = 0;
        for (String key : mData.keySet()) {
            List<Integer> list = mData.get(key);
            List<Line> lines = new ArrayList<Line>();
            List<PointValue> values = new ArrayList<PointValue>();
            for (int j = 0; j < list.size(); ++j) {
                values.add(new PointValue(j, list.get(j)));
            }
            Line line = new Line(values);
            line.setColor(ChartUtils.COLORS[i]);
            line.setShape(shape);
            line.setCubic(isCubic);
            line.setFilled(isFilled);
            line.setHasLabels(hasLabels);
            line.setHasLabelsOnlyForSelected(hasLabelForSelected);
            line.setHasLines(hasLines);
            line.setHasPoints(hasPoints);
            if (pointsHaveDifferentColor) {
                line.setPointColor(ChartUtils.COLORS[(i + 1) % ChartUtils.COLORS.length]);
            }
            lines.add(line);
            LineChartData data = new LineChartData(lines);

            if (hasAxes) {
                Axis axisX = new Axis();
                Axis axisY = new Axis().setHasLines(true);
                if (hasAxesNames) {
                    axisX.setName(key);
                    axisY.setName(mRes.getString(R.string.test_gradle));
                }
                data.setAxisXBottom(axisX);
                data.setAxisYLeft(axisY);
            } else {
                data.setAxisXBottom(null);
                data.setAxisYLeft(null);
            }
            data.setBaseValue(Float.NEGATIVE_INFINITY);
            mChartList.get(i).setLineChartData(data);
            i++;
        }

    }

    protected int onBindLayout() {
        return R.layout.activity_test_record;
    }
}
